<template>
  <div class="room-management">
    <div class="page-header">
      <h2>🏢 会议室管理</h2>
      <a-button type="primary" @click="showAddModal">
        <PlusOutlined /> 添加新会议室
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="rooms"
      :loading="loading"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'facilities'">
          <a-tag v-for="(facility, index) in record.facilities" :key="index" color="blue">
            {{ facility }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ record.status.toUpperCase() }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" size="small" @click="showEditModal(record)">
              编辑
            </a-button>
            <a-button type="primary" danger size="small" @click="handleDelete(record.id)">
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- Add/Edit Room Modal -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalMode === 'add' ? '添加新会议室' : `编辑会议室 - ${formState.name}`"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirm-loading="modalLoading"
      width="800px"
    >
      <!-- 标签切换 -->
      <a-tabs v-model:activeKey="activeTab">
        <!-- 基本信息标签 -->
        <a-tab-pane key="basic" tab="📋 基本信息">
          <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            layout="vertical"
          >
            <a-form-item label="会议室名称" name="name">
              <a-input v-model:value="formState.name" placeholder="例如: 会议室A" />
            </a-form-item>

            <a-form-item label="容量" name="capacity">
              <a-input-number
                v-model:value="formState.capacity"
                :min="1"
                placeholder="可容纳人数"
                style="width: 100%"
              />
            </a-form-item>

            <a-form-item label="位置" name="location">
              <a-input v-model:value="formState.location" placeholder="例如: A栋3楼" />
            </a-form-item>

            <a-form-item label="设施" name="facilities">
              <a-select
                v-model:value="formState.facilities"
                mode="tags"
                placeholder="添加设施"
                style="width: 100%"
              >
                <a-select-option value="投影仪">投影仪</a-select-option>
                <a-select-option value="白板">白板</a-select-option>
                <a-select-option value="视频会议">视频会议</a-select-option>
                <a-select-option value="电视屏幕">电视屏幕</a-select-option>
                <a-select-option value="音响系统">音响系统</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="状态" name="status">
              <a-select v-model:value="formState.status">
                <a-select-option value="active">可用</a-select-option>
                <a-select-option value="inactive">不可用</a-select-option>
                <a-select-option value="maintenance">维护中</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <!-- 开放时间标签 -->
        <a-tab-pane key="schedule" tab="⏰ 开放时间" :disabled="modalMode === 'add'">
          <a-alert
            message="💡 提示：每个会议室可以设置独立的开放时间，勾选日期即为开放，取消勾选则为关闭。"
            type="info"
            show-icon
            style="margin-bottom: 20px"
          />

          <div v-if="loadingSchedule" style="text-align: center; padding: 40px">
            <a-spin tip="加载时间表中..." />
          </div>

          <div v-else>
            <a-button 
              type="dashed" 
              @click="createDefaultSchedule" 
              style="margin-bottom: 16px"
              v-if="roomSchedules.length === 0"
            >
              创建默认时间表 (周一至周五 8:00-18:00)
            </a-button>

            <a-table
              :columns="scheduleColumns"
              :data-source="roomSchedules"
              :pagination="false"
              size="small"
              row-key="day_of_week"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'day_name'">
                  <strong>{{ getDayName(record.day_of_week) }}</strong>
                </template>

                <template v-else-if="column.key === 'open_time'">
                  <a-time-picker
                    v-model:value="record.open_time"
                    format="HH:mm"
                    :disabled="!record.is_available"
                    style="width: 120px"
                  />
                </template>

                <template v-else-if="column.key === 'close_time'">
                  <a-time-picker
                    v-model:value="record.close_time"
                    format="HH:mm"
                    :disabled="!record.is_available"
                    style="width: 120px"
                  />
                </template>

                <template v-else-if="column.key === 'is_available'">
                  <a-checkbox v-model:checked="record.is_available" @change="handleScheduleAvailableChange(record)">
                    开放
                  </a-checkbox>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getRooms, createRoom, updateRoom, deleteRoom } from '@/services/roomService'
import { 
  getRoomSchedule, 
  createDefaultSchedule as apiCreateDefaultSchedule,
  updateSchedule,
  createSchedule
} from '@/services/scheduleService'

const loading = ref(false)
const loadingSchedule = ref(false)
const rooms = ref([])
const modalVisible = ref(false)
const modalMode = ref('add')
const modalLoading = ref(false)
const formRef = ref(null)
const currentRoomId = ref(null)
const activeTab = ref('basic')
const roomSchedules = ref([])

const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const columns = [
  { title: '会议室名称', dataIndex: 'name', key: 'name' },
  { title: '容量', dataIndex: 'capacity', key: 'capacity' },
  { title: '位置', dataIndex: 'location', key: 'location' },
  { title: '设施', dataIndex: 'facilities', key: 'facilities' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action', width: 200 },
]

const scheduleColumns = [
  { title: '星期', key: 'day_name', width: 100 },
  { title: '开放时间', key: 'open_time', width: 150 },
  { title: '关闭时间', key: 'close_time', width: 150 },
  { title: '启用', key: 'is_available', width: 100 },
]

const formState = reactive({
  name: '',
  capacity: 1,
  location: '',
  facilities: [],
  status: 'active',
})

const rules = {
  name: [{ required: true, message: '请输入会议室名称' }],
  capacity: [{ required: true, message: '请输入容量' }],
  location: [{ required: true, message: '请输入位置' }],
  status: [{ required: true, message: '请选择状态' }],
}

const fetchRooms = async () => {
  loading.value = true
  try {
    rooms.value = await getRooms()
  } catch (error) {
    message.error('加载会议室列表失败')
  } finally {
    loading.value = false
  }
}

const fetchRoomSchedule = async (roomId) => {
  loadingSchedule.value = true
  try {
    const schedules = await getRoomSchedule(roomId)
    
    // 初始化所有星期的数据
    roomSchedules.value = Array.from({ length: 7 }, (_, day) => {
      const existing = schedules.find(s => s.day_of_week === day)
      if (existing) {
        return {
          id: existing.id,
          day_of_week: day,
          open_time: dayjs(existing.open_time, 'HH:mm:ss'),
          close_time: dayjs(existing.close_time, 'HH:mm:ss'),
          is_available: existing.is_available
        }
      } else {
        return {
          id: null,
          day_of_week: day,
          open_time: dayjs('08:00', 'HH:mm'),
          close_time: dayjs('18:00', 'HH:mm'),
          is_available: false
        }
      }
    })
  } catch (error) {
    message.error('加载时间表失败')
  } finally {
    loadingSchedule.value = false
  }
}

const showAddModal = () => {
  modalMode.value = 'add'
  modalVisible.value = true
  activeTab.value = 'basic'
  resetForm()
}

const showEditModal = async (room) => {
  modalMode.value = 'edit'
  currentRoomId.value = room.id
  formState.name = room.name
  formState.capacity = room.capacity
  formState.location = room.location
  formState.facilities = room.facilities || []
  formState.status = room.status
  activeTab.value = 'basic'
  modalVisible.value = true
  
  // 加载时间表
  await fetchRoomSchedule(room.id)
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true

    const roomData = { ...formState }

    if (modalMode.value === 'add') {
      const newRoom = await createRoom(roomData)
      message.success('会议室创建成功')
      currentRoomId.value = newRoom.id
    } else {
      await updateRoom(currentRoomId.value, roomData)
      
      // 保存时间表
      await saveSchedules()
      
      message.success('会议室更新成功')
    }

    modalVisible.value = false
    fetchRooms()
  } catch (error) {
    if (error.response) {
      message.error(error.response.data.detail || '操作失败')
    }
  } finally {
    modalLoading.value = false
  }
}

const saveSchedules = async () => {
  for (const schedule of roomSchedules.value) {
    const scheduleData = {
      room_id: currentRoomId.value,
      day_of_week: schedule.day_of_week,
      is_available: schedule.is_available,
      open_time: schedule.open_time.format('HH:mm:ss'),
      close_time: schedule.close_time.format('HH:mm:ss')
    }
    
    try {
      if (schedule.id) {
        // 更新现有时间表
        const updateData = { ...scheduleData }
        delete updateData.room_id
        await updateSchedule(schedule.id, updateData)
      } else if (schedule.is_available) {
        // 创建新时间表（仅当启用时）
        await createSchedule(scheduleData)
      }
    } catch (error) {
      console.error(`保存时间表失败 (Day ${schedule.day_of_week}):`, error)
    }
  }
}

const createDefaultSchedule = async () => {
  try {
    await apiCreateDefaultSchedule(currentRoomId.value)
    message.success('默认时间表创建成功')
    await fetchRoomSchedule(currentRoomId.value)
  } catch (error) {
    message.error(error.response?.data?.detail || '创建默认时间表失败')
  }
}

const handleScheduleAvailableChange = (record) => {
  if (!record.is_available) {
    record.open_time = dayjs('00:00', 'HH:mm')
    record.close_time = dayjs('00:00', 'HH:mm')
  } else {
    record.open_time = dayjs('08:00', 'HH:mm')
    record.close_time = dayjs('18:00', 'HH:mm')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

const handleDelete = (roomId) => {
  Modal.confirm({
    title: '删除会议室',
    content: '确定要删除这个会议室吗？此操作无法撤销。',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteRoom(roomId)
        message.success('会议室删除成功')
        fetchRooms()
      } catch (error) {
        message.error(error.response?.data?.detail || '删除会议室失败')
      }
    },
  })
}

const resetForm = () => {
  formState.name = ''
  formState.capacity = 1
  formState.location = ''
  formState.facilities = []
  formState.status = 'active'
  roomSchedules.value = []
  formRef.value?.resetFields()
}

const getStatusColor = (status) => {
  const colors = {
    active: 'green',
    inactive: 'default',
    maintenance: 'orange',
  }
  return colors[status] || 'default'
}

const getDayName = (dayNumber) => {
  return dayNames[dayNumber] || ''
}

onMounted(() => {
  fetchRooms()
})
</script>

<style scoped>
.room-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #262626;
}
</style>
